package com.thinkcms.security.custom;

import com.thinkcms.core.api.BaseRedisService;
import com.thinkcms.core.config.ThinkCmsConfig;
import com.thinkcms.core.constants.Constants;
import com.thinkcms.core.utils.Checker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import java.util.concurrent.TimeUnit;

public class CustomJwtTokenStore extends JwtTokenStore {

    @Autowired
    BaseRedisService baseRedisService;

    @Autowired
    ThinkCmsConfig thinkCmsConfig;

    public CustomJwtTokenStore(JwtAccessTokenConverter jwtTokenEnhancer) {
        super(jwtTokenEnhancer);
    }

    @Override
    public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
        //添加Jwt Token白名单,将Jwt以jti为Key存入redis中，并保持与原Jwt有一致的时效性
        if(!thinkCmsConfig.getAllowMultiLogin()){
            if(authentication.getPrincipal() instanceof CustomJwtUser){
                CustomJwtUser customJwtUser=(CustomJwtUser)authentication.getPrincipal();
                String userId=customJwtUser.getUserId();
                if (Checker.BeNotBlank(userId)) {
                    baseRedisService.set(Constants.AllowMultiLoginKey+userId, token.getValue(), token.getExpiresIn(), TimeUnit.SECONDS);
                }
            }
        }
        super.storeAccessToken(token, authentication);
    }
}
